package ourfilter;

import interfaces.Writeable;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.sql.Timestamp;
import java.util.Date;

import TransferObjekts.Line;
import pipes.Pipe;

public class OurSink implements Runnable, Writeable<Line> {

	private Pipe<Line> input;
	private BufferedWriter bw = null;
	private String pathToDest = "";

	public OurSink(Pipe<Line> input, String pathToDest) {
		this.input = input;
		input.setOut(this);
		this.pathToDest = pathToDest;
	}

	private void writeToFile(Line line) {
		try {
			if (bw == null) {
				bw = new BufferedWriter(new FileWriter(this.pathToDest));
			}
			bw.write(line.getLine() + " (line " + line.getLineNumber() + ")");
			bw.newLine();
		} catch (IOException io) {
			io.printStackTrace();
		}
	}

	public void run() {
		System.out.println("started " + new Timestamp(new Date().getTime()));
		Line line = null;
		do {
			try {
				line = input.read();
				write(line);
			} catch (StreamCorruptedException e) {
				e.printStackTrace();
			}
		} while (line != null);
		try {
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("finished " + new Timestamp(new Date().getTime()));
	}

	@Override
	public void write(Line line) throws StreamCorruptedException {
		if (line != null) {
			writeToFile(line);
		} else {
			try {
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
